package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/28 16:14
 */
public class JZSolution034 {
    public boolean isAlienSorted(String[] words, String order) {
        Map<Character,Integer> orderMap = new HashMap<>();
        for (int i = 0; i < order.length(); i++) {
            orderMap.put(order.charAt(i),i);
        }
        for (int i = 0; i < words.length-1; i++) {
            if(compare(words[i],words[i+1],orderMap)==false){
                return false;
            }
        }
        return true;
    }

    private boolean compare(String word1, String word2, Map<Character, Integer> orderMap) {
        int length1 = word1.length();
        int length2 = word2.length();
        int minLength = Math.min(length1,length2);
        for (int i = 0; i < minLength ; i++) {
            Integer index1 = orderMap.get(word1.charAt(i));
            Integer index2 = orderMap.get(word2.charAt(i));
            if(index1<index2){
                return true;
            }else if(index1>index2){
                return false;
            }
        }
        if(word1.length()<=word2.length()){
            return true;
        }else {
            return false;
        }
    }

    @Test
    public void test01(){
        String[] words = {"hello","leetcode"};
        String order = "hlabcdefgijkmnopqrstuvwxyz";
        boolean alienSorted = isAlienSorted(words, order);
        System.out.println(alienSorted);
    }

    @Test
    public void test02(){
        String[] words = {"word","world","row"};
        String order = "worldabcefghijkmnpqstuvxyz";
        boolean alienSorted = isAlienSorted(words, order);
        System.out.println(alienSorted);
    }

    @Test
    public void test03(){
        String[] words = {"apple","app"};
        String order = "abcdefghijklmnopqrstuvwxyz";
        boolean alienSorted = isAlienSorted(words, order);
        System.out.println(alienSorted);
    }
}
